package com.gulimall.ware.service.impl;

import com.alibaba.nacos.client.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gulimall.common.constant.WareConstant;
import com.gulimall.ware.entity.PurchaseDetailEntity;
import com.gulimall.ware.service.PurchaseDetailService;
import com.gulimall.ware.service.WareSkuService;
import com.gulimall.ware.vo.MergeVo;
import com.gulimall.ware.vo.PurchaseDoneVo;
import com.gulimall.ware.vo.PurchaseItemsDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.beans.Transient;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gulimall.common.utils.PageUtils;
import com.gulimall.common.utils.Query;

import com.gulimall.ware.dao.PurchaseDao;
import com.gulimall.ware.entity.PurchaseEntity;
import com.gulimall.ware.service.PurchaseService;
import org.springframework.util.CollectionUtils;

@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        String status = (String) params.get("status");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.like("assignee_name", key);
        }
        if (StringUtils.isNotEmpty(status)) {
            wrapper.like("status", status);
        }
        IPage<PurchaseEntity> page = this.page(new Query<PurchaseEntity>().getPage(params), wrapper.orderByDesc("id"));

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryUnreceivePage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
                        .eq("status", 0)
                        .or()
                        .eq("status", 1));
        return new PageUtils(page);
    }

    @Transient
    @Override
    public void merge(MergeVo vo) {
        Long purchaseId = vo.getPurchaseId();
        if (Objects.isNull(purchaseId)) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        List<Long> items = vo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(id -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(id);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).filter(item -> {
            Integer status = item.getStatus();
            return WareConstant.PurchaseStatusEnum.CREATED.getCode() == status || WareConstant.PurchaseStatusEnum.ASSIGNED.getCode() == status;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(collect);
        this.update(new UpdateWrapper<PurchaseEntity>()
                .set("update_time", new Date())
                .eq("id", purchaseId)
        );
    }

    @Transient
    @Override
    public void received(List<Long> ids) {
        //1.确认采购单状态
        List<PurchaseEntity> purchaseEntitys = this.list(new QueryWrapper<PurchaseEntity>().in("id", ids));
        List<PurchaseEntity> collect = purchaseEntitys.stream()
                //过滤
                .filter(item -> {
                            Integer status = item.getStatus();
                            return WareConstant.PurchaseStatusEnum.CREATED.getCode() == status || WareConstant.PurchaseStatusEnum.ASSIGNED.getCode() == status;
                        }
                )
                // 改变状态
                .peek(item -> {
                    item.setUpdateTime(new Date());
                    item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                }).collect(Collectors.toList());
        //2.改变采购单状态
        if (!CollectionUtils.isEmpty(collect)) {
            this.updateBatchById(collect);
            //3.改变采购项状态
            collect.forEach(item -> {
                // 查找 采购项目
                List<PurchaseDetailEntity> purchaseDetails = purchaseDetailService.listDetailByPurchaseId(item.getId());
                // 修改状态
                List<PurchaseDetailEntity> detailEntities = purchaseDetails.stream().peek(purchaseDetail -> purchaseDetail.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode())
                ).collect(Collectors.toList());
                purchaseDetailService.updateBatchById(detailEntities);
            });
        }
    }

    @Transient
    @Override
    public void done(PurchaseDoneVo vo) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        //1.改变采购单状态
        Long id = vo.getId();
        PurchaseEntity purchaseEntity = this.getById(id);
        purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
        purchaseEntity.setUpdateTime(new Date());
        //2.改变采购项状态
        List<PurchaseItemsDoneVo> purchaseItemsDoneVos = vo.getItems();
        boolean flag = true;
        for (PurchaseItemsDoneVo purchaseItemsDoneVo : purchaseItemsDoneVos) {
            // 查找 采购项目
            PurchaseDetailEntity purchaseDetail = purchaseDetailService.getById(purchaseItemsDoneVo.getItemId());
            if (purchaseItemsDoneVo.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                flag = false;
                purchaseDetail.setStatus(purchaseItemsDoneVo.getStatus());
            } else {
                purchaseDetail.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //3.添加库存
                wareSkuService.addStock(purchaseDetail.getSkuId(),purchaseDetail.getWareId(),purchaseDetail.getSkuNum());
            }

            // 修改状态
            purchaseDetailService.updateById(purchaseDetail);
        }
        if (!flag) {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        }
        this.updateById(purchaseEntity);


    }
}
